package com.ikdong.toodle.util;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.util.Log;

import com.ikdong.toodle.dao.AuthDAO;
import com.ikdong.toodle.exception.InvalidAccountException;
import com.ikdong.toodle.exception.TDException;
import com.ikdong.toodle.model.Authentication;

public class AuthManager {
	private AuthDAO dao;
	
	public AuthManager(Context context){
		dao = new AuthDAO(context);
	}
	
	public boolean auth(String email,String pass){
		boolean flag = false;
		try{
			Log.d(Constant.TAG, "Start to login......");
			
			String userid = ToodleHttpClient.getUserId(email, pass);
			if(userid==null){
				throw new InvalidAccountException("The email or password is invalid.");
			}			
			Log.d(Constant.TAG, "get userid: "+userid);
			
			
			String token = ToodleHttpClient.getSessionToken(userid);
			if(token==null){
				throw new TDException("","The Token is invalid.");
			}
			Log.d(Constant.TAG, "get token: "+token);
			
			String key = MD5(MD5(pass)+ToodleHttpClient.appToken+token);
			Log.d(Constant.TAG, "get key: "+key);
			
			Authentication auth = new Authentication();
			auth.setEmail(email);
			auth.setPass(pass);
			auth.setUserId(userid);
			auth.setKey(key);
			auth.setDateTime(new Date().getTime());
			flag = save(auth);
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthManager.login()", e);
		}
		
		return flag;
	}
	
	public boolean delete(){
		return dao.delete();
	}
	
	public boolean isKeyValid(){
		boolean flag = false;
		try{
			Authentication auth = this.get();
			if(auth!=null){
				long now = new Date().getTime();
				if((now-auth.getDateTime())<(4*3600*1000)){
					flag = true;
				}
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthManager.isKeyValid() error", e);
		}
		return flag;
	}
	
	public String getKey(){
		String key = null;
		Authentication auth = this.get();
		if(auth!=null){
			key = auth.getKey();
		}
		return key;
	}
	
	public boolean save(Authentication auth){
		boolean flag = false;
		try{
			dao.delete();
			flag = dao.add(auth);
		}catch(Exception e){
			Log.e(Constant.TAG, "AuthManager.isKeyValid() error", e);
		}
		return flag;
	}
	
	public Authentication get(){
		Authentication auth = null;
		List<Authentication> auths = dao.get();
		if(auths.size()>0){
			auth = auths.get(0);
		}
		return auth;
	}
	
	public void refreshKey() throws InvalidAccountException{
		Log.d(Constant.TAG, "AuthManager to refresh key....");
		Authentication auth = dao.get().get(0);
		if(!auth.isValid() && !auth(auth.getEmail(), auth.getPass())){
			Log.e(Constant.TAG, "AuthManager.refreshKey error");
			throw new InvalidAccountException("Failed to login Toodledo Service. Please relogin!");
		}
	}
	
	private String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}
}
